﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using app.Models;

namespace app
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);

            //
            Api.G.DB.ServerName = System.Configuration.ConfigurationManager.AppSettings["ConnectionServer"];
            Api.G.DB.DatabaseName = System.Configuration.ConfigurationManager.AppSettings["ConnectionDatabase"];
            Api.G.DB.UserName = System.Configuration.ConfigurationManager.AppSettings["ConnectionUsername"];
            Api.G.DB.Password = System.Configuration.ConfigurationManager.AppSettings["ConnectionPassword"];
            Api.ApiBase.AllowApiExemption = System.Configuration.ConfigurationManager.AppSettings["AllowApiExemption"] == "true";
        }

        void Session_Start(object sender, EventArgs e)
        {
            if (!Api.G.IsStarted) return;
            int page_view = int.Parse(FreeValue.GetValue("website.page_view", 0)); //网站的总访问量
            int page_view_today = int.Parse(FreeValue.GetValue("website.page_view_today", 0)); //网站当日访问量
            long view_timer = long.Parse(FreeValue.GetValue("website.view_timer", 0)); //当日访问量刷新计时器
            //1.增加网站总访问量
            page_view = page_view + 1;
            FreeValue.Set("website.page_view", page_view);
            //2.增加网站当日访问量
            //获取当前时间戳与计时器进行对比
            long now_time_stamp = long.Parse(Api.DateTimeEx.GetNowTimeStamp());
            if (now_time_stamp - view_timer > 86400000)
            {
                page_view_today = 0;
                FreeValue.Set("website.view_timer", now_time_stamp);
            }
            page_view_today = page_view_today + 1;
            FreeValue.Set("website.page_view_today", page_view_today);
        }

        void Session_End(object sender, EventArgs e)
        {
            //不是每次请求都调用
            //会话结束或过期时执行
            //不管在代码中显式的清空Session或者Session超时自动过期，此方法都将被调用

            // 从登陆服务器类中删除当前用户
            if(Session["user_inentity"] != null && Session["user_code"] != null && Session["token"] != null)
            {
                Api.LandingServer.RemoveUnit((Api.IDENTITY)Session["user_inentity"] + Session["user_code"].ToString(), Session["token"].ToString());
            }
        }

    }
}
